import router from './index'
import store from '../store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, removeToken } from '@/utils/cookie'
import { getPageTitle } from '@/utils/system'
import http from '@/utils/http'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/forget']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasUsername = store.getters.username
      if (hasUsername) {
        next()
      } else {
        await http.get('/user/current', null, false).then((response) => {
          store.dispatch('user/currentUserInfo', response.data)
        }).catch(() => {
          removeToken()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        })
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
